package com.onstar.cn.common.util;

import java.util.HashMap;
import java.util.Map;


import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.onstar.cn.common.kernel.KernelObject;

/**
 * 主要操作R，自动编译得到R文件的一些字段
 * 
 * @author 7828wc
 * 
 */
public class AppRUtils {
	private static final Map<String, Object> Type_Map_Resouce_Class = new HashMap<String, Object>();
	private static AppRUtils instance;
	private PackageInfo packageInfo;
	private static Class<?> RClass;

	private AppRUtils(Context context) {
		try {
			packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			RClass = forName(packageInfo.packageName + "." + "R");
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		if (packageInfo == null) {
			throw new RuntimeException("package info is null");
		}
	}

	public static AppRUtils getInstance(Context context) {
		if (instance == null) {
			instance = new AppRUtils(context);
		}
		return instance;
	}

	/**
	 * @param type
	 * @param name
	 * @return
	 */
	public Integer getResouceId(String type, String name) {
		Object resouce = Type_Map_Resouce_Class.get(type);
		if (resouce == null) {
			synchronized (type) {
				resouce = Type_Map_Resouce_Class.get(type);
				if (resouce == null) {
					resouce = forName(RClass.getName() + "$" + capitalize(type));
				}
				if (resouce != null) {
					Type_Map_Resouce_Class.put(type, resouce);
				}
			}
		}
		return resouce == null ? null : (Integer) KernelObject.get(resouce, name);
	}

	public Class<?> forName(String name) {
		try {
			return Class.forName(name);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String capitalize(String string) {
		char[] data = string.toCharArray();
		data[0] = Character.toLowerCase(data[0]);
		return String.valueOf(data);
	}
}
